package HTTP

import (
	"SQL/myDB"
	"net/http"
	"strconv"
)

//获取<添加群成员>界面的成员列表：
//s groupID string,pageIndex int,pageSize int
//r Message string,
//  [memeberID string,memberIcon string,memberNickname string]//添加memberIcon

func addGroupMember(w http.ResponseWriter, req *http.Request) {
	var (
		code   int         = Success
		msg    string      = ""
		result interface{} = nil
	)
	defer func() {
		writeResponse(code, msg, result, w)
	}()

	err := initHandle(w, req)
	if err != nil {
		code = errParseForm
		msg = err.Error()
		return
	}

	//fmt.Println(req.Form)
	groupID := req.FormValue("groupID")
	pageIndex, err := strconv.Atoi(req.FormValue("pageIndex"))
	if err != nil {
		code = errNotInt
		msg = err.Error()
		return
	}
	pageSize, err := strconv.Atoi(req.FormValue("pageSize"))
	if err != nil {
		code = errNotInt
		msg = err.Error()
		return
	}

	code, msg, result = dealAddGroupMember(groupID, pageIndex, pageSize)
}
func dealAddGroupMember(groupID string, pageIndex int, pageSize int) (code int, msg string, result interface{}) {
	if groupID == "" {
		code = errEmtpyID
		msg = "groupID is empty!"
		return
	}
	code, msg = IsGroupID(groupID)
	if code != Success {
		return
	}
	if pageIndex < 0 {
		code = errNegativeInt
		msg = "行号小于0"
		return
	}
	if pageSize > 50 {
		code = errRequestEntityTooLarge
		msg = "分页大小不应大于50"
		return
	}
	rows, err := myDB.QuerySql(`select id,icon,nickname
							 	from objects 
							 	where isUser = true and id not in (
								  	select userID from members 
								  	where groupID=$1 ) 
							 	limit $2 offset $3`, groupID, pageSize, pageIndex)
	if err != nil {
		code = errDBQueryFailed
		msg = err.Error()
		return
	}
	defer rows.Close()

	groupMember := make([]GroupMember, 0)
	for rows.Next() {
		var aMember GroupMember
		err = rows.Scan(&aMember.MemberID, &aMember.MemberIcon, &aMember.MemberNickname)
		if err != nil {
			code = errRowsScan
			msg = err.Error()
			break
		}
		groupMember = append(groupMember, aMember)
	}
	return Success, "", groupMember
}

func IsGroupID(groupID string) (int, string) {
	rows, err := myDB.QuerySql("select isUser from objects where id=$1", groupID)
	if err != nil {
		return errDBQueryFailed, err.Error()
	}
	defer rows.Close()
	if !rows.Next() {
		return errNotExistID, "groupID " + groupID + " not exist"
	}
	var isUser bool
	err = rows.Scan(&isUser)
	if err != nil {
		return errRowsScan, err.Error()
	}
	if isUser {
		return errInvalidID, groupID + " is user"
	}
	return Success, ""
}
